package com.jaya.budan.fragment;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.alibaba.fastjson.JSON;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.jaya.budan.R;
import com.jaya.budan.activity.GD_Map_Activity;
import com.jaya.budan.activity.GeRenTG_Activity;
import com.jaya.budan.activity.TaRen_Main_Activity;
import com.jaya.budan.activity.TiaoJian_ShaiXuan_Activity;
import com.jaya.budan.activity.TuiJian_More_Activity;
import com.jaya.budan.adapter.HorizontalListViewAdapter;
import com.jaya.budan.adapter.NearBy_ListView_Adapter;
import com.jaya.budan.base.BaseFragment;
import com.jaya.budan.bean.ListUser_Information;
import com.jaya.budan.bean.User_Limit;
import com.jaya.budan.connect.RequestConnect;
import com.jaya.budan.utils.ToolUtils;
import com.jaya.budan.utils.VolleyUtil;
import com.jaya.budan.views.HorizontalListView;
import com.jaya.budan.views.MyGridView;
import com.jaya.budan.views.MyListView;
import com.jwenfeng.library.pulltorefresh.BaseRefreshListener;
import com.jwenfeng.library.pulltorefresh.PullToRefreshLayout;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

public class NearByFragment extends BaseFragment implements View.OnClickListener {

    private Button btn_main_juli, btn_main_online;
    private ImageView iv_main_qiehuan, iv_main_ditu, iv_main_shaixuan;
    private MyListView main_listview;
    private MyGridView main_gridview;
    private LinearLayout ll_nearby_gerentg;
    private RelativeLayout rl_nearby_more;
    private PullToRefreshLayout topic_pull_layout;
    private HorizontalListView main_hlv;
    private String access_token;
    private ArrayList<User_Limit> user_limitList;
    private ArrayList<User_Limit> user_hlv_limitList;
    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_near_by, container, false);
        btn_main_juli = view.findViewById(R.id.btn_main_juli);
        btn_main_online = view.findViewById(R.id.btn_main_online);
        iv_main_qiehuan = view.findViewById(R.id.iv_main_qiehuan);
        iv_main_ditu = view.findViewById(R.id.iv_main_ditu);
        iv_main_shaixuan = view.findViewById(R.id.iv_main_shaixuan);
        main_listview = view.findViewById(R.id.main_listview);
        main_gridview = view.findViewById(R.id.main_gridview);
        main_hlv = view.findViewById(R.id.main_hlv);
        ll_nearby_gerentg = view.findViewById(R.id.ll_nearby_gerentg);
        rl_nearby_more = view.findViewById(R.id.rl_nearby_more);
        topic_pull_layout = view.findViewById(R.id.topic_pull_layout);
        user_limitList = new ArrayList<>();
        user_hlv_limitList = new ArrayList<>();
        Bundle bundle = getArguments();
        access_token = bundle.getString("access_token");
        postTJData();//推荐列表
        postData(1);
        btn_main_juli.setOnClickListener(this);
        btn_main_online.setOnClickListener(this);
        iv_main_qiehuan.setOnClickListener(this);
        iv_main_ditu.setOnClickListener(this);
        iv_main_shaixuan.setOnClickListener(this);
        ll_nearby_gerentg.setOnClickListener(this);
        rl_nearby_more.setOnClickListener(this);
        main_gridview.setVerticalSpacing(10);
        main_gridview.setHorizontalSpacing(10);
        main_listview.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                //判断ListView是否滑动到第一个Item的顶部
                if (view.getChildCount() > 0 && view.getFirstVisiblePosition() == 0 && view.getChildAt(0).getTop() >= view.getPaddingTop()) {
                    //解决滑动冲突，当滑动到第一个item，下拉刷新才起作用
                    topic_pull_layout.setEnabled(true);
                } else {
                    topic_pull_layout.setEnabled(false);
                }
            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {

            }
        });
        main_gridview.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                //判断ListView是否滑动到第一个Item的顶部
                if (view.getChildCount() > 0 && view.getFirstVisiblePosition() == 0 && view.getChildAt(0).getTop() >= view.getPaddingTop()) {
                    //解决滑动冲突，当滑动到第一个item，下拉刷新才起作用
                    topic_pull_layout.setEnabled(true);
                } else {
                    topic_pull_layout.setEnabled(false);
                }
            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {

            }
        });
        topic_pull_layout.setRefreshListener(new BaseRefreshListener() {
            @Override
            public void refresh() {
                topic_pull_layout.finishRefresh();//结束刷新
            }

            @Override
            public void loadMore() {
                topic_pull_layout.finishLoadMore();//结束加载更多
            }
        });
        main_hlv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent(getActivity(), TaRen_Main_Activity.class);
                intent.putExtra("access_token", access_token);
                intent.putExtra("roomId", position + "");
                intent.putExtra("uid", user_hlv_limitList.get(position).getUid());
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(intent);
            }
        });
        main_listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent(getActivity(), TaRen_Main_Activity.class);
                intent.putExtra("access_token", access_token);
                intent.putExtra("roomId", position + "");
                intent.putExtra("uid", user_limitList.get(position).getUid());
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(intent);
            }
        });
        main_gridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent(getActivity(), TaRen_Main_Activity.class);
                intent.putExtra("access_token", access_token);
                intent.putExtra("roomId", position + "");
                intent.putExtra("uid", user_limitList.get(position).getUid());
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(intent);
            }
        });
        return view;
    }

    public void postData(int tab){
        SharedPreferences preferences = getActivity().getSharedPreferences("user_limit", Context.MODE_PRIVATE);
        String str_json = preferences.getString("object", "");
        Log.d("tiaojian_main", str_json);
        if (! ToolUtils.isEmpty(str_json)){
            ListUser_Information information = JSON.parseObject(str_json, ListUser_Information.class);
            JSONArray list_age = new JSONArray();
            JSONArray list_height = new JSONArray();
            JSONArray list_weight = new JSONArray();
            if (information.getAge().size() > 0){
                for (int i=0; i<information.getAge().size(); i++){
                    list_age.put(information.getAge().get(i));
                }
            }
            if (information.getHeight().size() > 0) {
                for (int i = 0; i < information.getHeight().size(); i++) {
                    list_height.put(information.getHeight().get(i));
                }
            }
            if (information.getWeight().size() > 0){
                for (int i=0; i<information.getWeight().size(); i++){
                    list_weight.put(information.getWeight().get(i));
                }
            }
            JSONObject object = new JSONObject();
            try {
                object.put("tab", tab);//按照距离显示 2在线列表 默认1
                object.put("lng", information.getLng());//经度 默认当前请求用户的位置
                object.put("lat", information.getLat());//纬度 默认当前请求用户的位置
                object.put("is_vip", 0);//是否是vip 0无限制 1会员
                object.put("is_head", 0);//是否有头像 0无限制 1有头像
                object.put("is_online", 0);//是否在线 0不限制 1在线
                object.put("age", list_age);//年龄范围 []不限制 [20,30] 20到30
                object.put("height", list_height);//身高范围 []不限制 [0,130] 0到130
                object.put("weight", list_weight);//体重范围 []不限制 [0,130] 0到130
                object.put("type", information.getType());//类型value数组 []不限制 [1,2]
                object.put("role", information.getRole());//角色value数组 []不限制 [1,2]
                object.put("face", information.getFace());//形象value数组 []不限制 [1,2]
            } catch (JSONException e) {
                e.printStackTrace();
            }
            postData(object);
        } else {
            SharedPreferences preferences2 = getActivity().getSharedPreferences("gd_amapLocation", Context.MODE_PRIVATE);
            JSONArray list_age = new JSONArray();
            JSONObject object = new JSONObject();
            try {
                object.put("tab", tab);//按照距离显示 2在线列表 默认1
                object.put("lng", preferences2.getString("longitude", ""));//经度 默认当前请求用户的位置
                object.put("lat", preferences2.getString("latitude", ""));//纬度 默认当前请求用户的位置
                object.put("is_vip", 0);//是否是vip 0无限制 1会员
                object.put("is_head", 0);//是否有头像 0无限制 1有头像
                object.put("is_online", 0);//是否在线 0不限制 1在线
                object.put("age", list_age);//年龄范围 []不限制 [20,30] 20到30
                object.put("height", list_age);//身高范围 []不限制 [0,130] 0到130
                object.put("weight", list_age);//体重范围 []不限制 [0,130] 0到130
                object.put("type", list_age);//类型value数组 []不限制 [1,2]
                object.put("role", list_age);//角色value数组 []不限制 [1,2]
                object.put("face", list_age);//形象value数组 []不限制 [1,2]
            } catch (JSONException e) {
                e.printStackTrace();
            }
            postData(object);
        }

    }

    public static NearByFragment newInstance() {
        Bundle args = new Bundle();
        NearByFragment fragment = new NearByFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @SuppressLint("NonConstantResourceId")
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_main_juli:
                postData(1);
                btn_main_juli.setBackgroundResource(R.drawable.login_login);
                btn_main_online.setBackgroundResource(R.drawable.login_exit);
                break;
            case R.id.btn_main_online:
                postData(2);
                btn_main_juli.setBackgroundResource(R.drawable.login_exit);
                btn_main_online.setBackgroundResource(R.drawable.login_login);
                break;
            case R.id.iv_main_qiehuan:
                if (main_listview.getVisibility() == View.VISIBLE){
                    main_listview.setVisibility(View.GONE);
                    main_gridview.setVisibility(View.VISIBLE);
                    iv_main_qiehuan.setImageResource(R.mipmap.iv_main_qiehuan_lv);
                } else {
                    main_listview.setVisibility(View.VISIBLE);
                    main_gridview.setVisibility(View.GONE);
                    iv_main_qiehuan.setImageResource(R.mipmap.iv_main_qiehuan);
                }
                break;
            case R.id.iv_main_ditu:
                Intent intent = new Intent(getActivity(), GD_Map_Activity.class);
                intent.putExtra("access_token", access_token);
                startActivity(intent);
                break;
            case R.id.iv_main_shaixuan:
                Intent intent1 = new Intent(getActivity(), TiaoJian_ShaiXuan_Activity.class);
                intent1.putExtra("access_token", access_token);
                startActivity(intent1);
                break;
            case R.id.ll_nearby_gerentg:
                Intent intent0 = new Intent(getActivity(), GeRenTG_Activity.class);
                intent0.putExtra("access_token", access_token);
                startActivity(intent0);
                break;
            case R.id.rl_nearby_more:
                Intent intent2 = new Intent(getActivity(), TuiJian_More_Activity.class);
                intent2.putExtra("access_token", access_token);
                intent2.putExtra("user_hlv_limitList", user_hlv_limitList);
                startActivity(intent2);
                break;
            default:
                break;
        }
    }

    /**
     * 网络请求
     * @param object
     */
    private void postData(JSONObject object) {
        Log.d("main", object.toString());
        JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, RequestConnect.main_User_Url + access_token + "&page=1&limit=10", object, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject jsonObject) {
                Log.d("main-list", jsonObject.toString());
                try {
                    int code = jsonObject.optInt("code");
                    int status = jsonObject.optInt("status");
                    String message = jsonObject.getString("message");
                    if (code == 0) {
                        Gson gson = new Gson();
                        JSONArray info = jsonObject.getJSONArray("info");
                        user_limitList = gson.fromJson(info.toString(), new TypeToken<List<User_Limit>>(){}.getType());
//                        Log.d("main-list", JSON.toJSONString(user_limitList));
                        main_listview.setAdapter(new NearBy_ListView_Adapter(getActivity(), user_limitList, 1));
                        main_gridview.setAdapter(new NearBy_ListView_Adapter(getActivity(), user_limitList, 2));
                    } else {
                        ToolUtils.showToast(getActivity(), message);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                ToolUtils.showToast(getActivity(), "网络请求失败，请稍后重试~");
            }
        });
        request.setTag(this);
        VolleyUtil.getQueue(getActivity()).add(request);
    }

    /**
     * 网络请求
     */
    private void postTJData() {
        JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, RequestConnect.main_TJ_User_Url + access_token + "&page=1&limit=10", null, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject jsonObject) {
                Log.d("main-tj", jsonObject.toString());
                try {
                    int code = jsonObject.optInt("code");
                    int status = jsonObject.optInt("status");
                    String message = jsonObject.getString("message");
                    if (code == 0) {
                        Gson gson = new Gson();
                        JSONArray info = jsonObject.getJSONArray("info");
                        user_hlv_limitList = gson.fromJson(info.toString(), new TypeToken<ArrayList<User_Limit>>(){}.getType());
                        if (user_hlv_limitList.size() > 0){
                            // 获取屏幕宽高
                            int screenWidth = getActivity().getWindowManager().getDefaultDisplay().getWidth(); // 屏幕宽（像素，如：480px）
                            HorizontalListViewAdapter horizontalListViewAdapter = new HorizontalListViewAdapter(getActivity(), screenWidth, user_hlv_limitList, null, 0);
                            main_hlv.setAdapter(horizontalListViewAdapter);
                        }
                    } else {
                        ToolUtils.showToast(getActivity(), message);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                ToolUtils.showToast(getActivity(), "网络请求失败，请稍后重试~");
            }
        });
        request.setTag(this);
        VolleyUtil.getQueue(getActivity()).add(request);
    }

    @Override
    public void onResume() {
        super.onResume();
        postData(1);
    }
}
